import { type Dexie as DexieType, type EntityTable } from 'dexie';
import { Dexie } from '@/assets/js/dexie';
import { GigaAvaliable, keyPrefix } from '@/entrypoints/gigab2b.content/hook/useAvaliableDB';

export type DB = DexieType & {
  gigaAvaliable: EntityTable<GigaAvaliable, 'id'>;
};

// 获取 db 数据库存
export async function getAvaliableDB(gigaCatetoryName: string) {
  // @ts-ignore
  const db = new Dexie(keyPrefix + gigaCatetoryName) as DB;
  db.version(1).stores({
    gigaAvaliable: '++id,skuInfo,timeStamp,avaliable',
  });
  return db;
}
// 获取分类下所有货号的库存
export async function getCatetoryAvaliable(gigaCatetoryName: string, db: DB | null = null) {
  if (!db) {
    db = await getAvaliableDB(gigaCatetoryName);
  }
  const result = await db.gigaAvaliable.toArray();
  // console.log(result);
  return result;
}

// 获取当前分类的仓库在今天中有多少产品获取到库存
export async function getTodayItemsCount(gigaCatetoryName: string, db: DB | null = null) {
  if (!db) {
    db = await getAvaliableDB(gigaCatetoryName);
  }
  const today = new Date();
  const startOfDay = new Date(today.setHours(0, 0, 0, 0)).getTime();
  const endOfDay = new Date(today.setHours(23, 59, 59, 999)).getTime();

  // 查询当天所有数据项
  const todayItems = await db.gigaAvaliable
    .where('timeStamp')
    .between(startOfDay, endOfDay)
    .toArray();

  // 使用Set来过滤重复的skuInfo
  const uniqueSkuInfos = new Set<string>();
  todayItems.forEach((item) => {
    uniqueSkuInfos.add(item.skuInfo);
  });

  return uniqueSkuInfos.size;
}

// 清空分类下的库存
export async function clearCatetoryAvaliable(gigaCatetoryName: string, db: DB | null = null) {
  if (!db) {
    db = await getAvaliableDB(gigaCatetoryName);
  }
  await db.gigaAvaliable.clear();
}

// 获取单个分类的库存,目前是不可用的状态,转为使用并行队列来获取
// export async function fetchAvaliable(
//   gigaCatetoryDirectoryHandle: FileSystemDirectoryHandle,
//   taskConcurrencyLimit = 6,
// ) {
//   const skuIdInfoDirectoryHandles = await getAllFDirectoryHandleByDirectoryHandle(
//     gigaCatetoryDirectoryHandle!,
//   );
//   const skuInfos = skuIdInfoDirectoryHandles.map((skuIdInfoDirectoryHandle) => {
//     return skuIdInfoDirectoryHandle.name;
//   });
//   const timeStamp = Date.now();
//   const catetoryName = gigaCatetoryDirectoryHandle.name;
//   const db = await getAvaliableDB(catetoryName);
//   await concurrentLimit(
//     skuInfos.map((skuInfo) => async () => {
//       const [gigaSku, gigaProductId] = getGigaSkuAndProductId(skuInfo);
//       let data = {} as Omit<GigaAvaliable, 'id'>;
//       try {
//         const result = await getProductPriceInfo(gigaProductId);
//         if (result.code !== 200) {
//           console.log(result);
//         }
//         data = {
//           skuInfo,
//           timeStamp,
//           avaliable: result.data.quantity.quantity,
//         };
//         await db.gigaAvaliable.add(data);
//       } catch (error) {
//         toast.error(`${skuInfo}: 获取库存失败 ${(error as Error).message}`);
//       }
//     }),
//     taskConcurrencyLimit,
//   );
// }

// 获取所有的分类库存,目前是不可用的状态,转为使用并行队列来获取
// export async function fetchAllAvaliable(
//   gigaCatetoryDirectoryHandles: FileSystemDirectoryHandle[],
//   taskConcurrencyLimit: number,
// ) {
//   for (const gigaCatetoryDirectoryHandle of gigaCatetoryDirectoryHandles) {
//     await fetchAvaliable(gigaCatetoryDirectoryHandle, taskConcurrencyLimit);
//     toast.success(`完成 ${gigaCatetoryDirectoryHandle.name} 分类下的所有的产品获取操作`);
//   }
// }

// 获取一定时间范围内的库存减少量
export interface AvaliableItem {
  skuInfo: string;
  reduction: number;
  maxAvaliable: number;
  minAvaliable: number;
}
export async function getAvaliableCategoryReduction(
  startTimestamp: number,
  endTimestamp: number,
  gigaCatetoryName: string,
  db: DB | null = null,
): Promise<Array<AvaliableItem>> {
  if (!db) {
    db = await getAvaliableDB(gigaCatetoryName);
  }
  // 查询时间范围内的所有数据项
  const items = await db.gigaAvaliable
    .where('timeStamp')
    .between(startTimestamp, endTimestamp)
    .toArray();

  // 按skuInfo分组
  const itemsBySku = new Map<string, GigaAvaliable[]>();
  items.forEach((item) => {
    if (!itemsBySku.has(item.skuInfo)) {
      itemsBySku.set(item.skuInfo, []);
    }
    itemsBySku.get(item.skuInfo)!.push(item);
  });

  // 计算每个skuInfo的减少量
  const results: Array<AvaliableItem> = [];

  itemsBySku.forEach((items, skuInfo) => {
    // 过滤掉avaliable为NaN的项
    const validItems = items.filter((item) => !Number.isNaN(item.avaliable));

    if (validItems.length === 0) {
      return; // 跳过没有有效数据的sku
    }

    // 计算最大值和最小值
    const avaliables = validItems.map((item) => item.avaliable);
    const maxAvaliable = Math.max(...avaliables);
    const minAvaliable = Math.min(...avaliables);
    const reduction = maxAvaliable - minAvaliable;

    results.push({
      skuInfo,
      reduction,
      maxAvaliable,
      minAvaliable,
    });
  });

  return results;
}

// 获取特定分类下,所有产品在特定天数中最新的库存数量
export async function getCategoryAvaliableByDay(
  timeStamp: number,
  gigaCatetoryName: string,
  db: DB | null = null,
) {
  if (!db) {
    db = await getAvaliableDB(gigaCatetoryName);
  }
  const date = new Date(timeStamp);
  const startTimestamp = new Date(date.setHours(0, 0, 0, 0)).getTime();
  const endTimestamp = new Date(date.setHours(23, 59, 59, 999)).getTime();
  const items = await db.gigaAvaliable
    .where('timeStamp')
    .between(startTimestamp, endTimestamp)
    .toArray();

  // 按skuInfo分组
  const itemsBySku = new Map<string, GigaAvaliable[]>();
  items.forEach((item) => {
    if (!itemsBySku.has(item.skuInfo)) {
      itemsBySku.set(item.skuInfo, []);
    }
    itemsBySku.get(item.skuInfo)!.push(item);
  });

  const results: Array<{
    skuInfo: string;
    avaliable: number;
    timeStamp: number;
  }> = [];

  itemsBySku.forEach((items, skuInfo) => {
    // 过滤掉avaliable为NaN的项
    const validItems = items.filter((item) => !Number.isNaN(item.avaliable));

    if (validItems.length === 0) {
      return; // 跳过没有有效数据的sku
    }

    // 计算按最新时间下的库存数量
    // validItems 按时间从最新到最旧排序
    validItems.sort((a, b) => b.timeStamp - a.timeStamp);
    const avaliable = validItems[0].avaliable;

    results.push({
      skuInfo,
      avaliable,
      timeStamp: validItems[0].timeStamp,
    });
  });
  return results;
}

// 获取特定货号下,在特定天数中最新的库存数量
export async function getSkuInfoAvaliableByDay(
  skuInfo: string,
  timeStamp: number,
  gigaCatetoryName: string,
  db: DB | null = null,
) {
  if (!db) {
    db = await getAvaliableDB(gigaCatetoryName);
  }
  const date = new Date(timeStamp);
  const startTimestamp = new Date(date.setHours(0, 0, 0, 0)).getTime();
  const endTimestamp = new Date(date.setHours(23, 59, 59, 999)).getTime();
  const items = await db.gigaAvaliable
    .where('timeStamp')
    .between(startTimestamp, endTimestamp)
    .and((item) => item.skuInfo === skuInfo)
    .toArray();

  const validItems = items.filter((item) => !Number.isNaN(item.avaliable));

  if (validItems.length === 0) {
    return null;
  }

  validItems.sort((a, b) => b.timeStamp - a.timeStamp);

  return validItems[0];
}
